import 'dart:async';

import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/education_comment_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_children_entity.dart';
import 'package:flutter/services.dart';

///人脸识别后的课程详情-》评价
class EvaluateDetailController extends GetxController {
  /// 创建FocusNode实例(聚焦)
  FocusNode focusNode = FocusNode();
  FocusNode focusNode2 = FocusNode();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();
  List<EducationCommentListEntity>? list = [];
  List<EducationCommentListEntity>? listMe = [];
  bool who = true;

  /// 搜索条件
  String? searchX;

  /// 用户问题
  String userAddComment = '';

  ///----------------------------底部弹框UI------------------------------
  final GlobalKey<CustomEasyRefreshListState> globalKeyDialog = GlobalKey();

  ///点击一级评论的id
  String firstLevelCommentId = '';
  RxBool first = false.obs;

  ///上一个点击的节点
  GetChildrenChildren? tobGetChildrenChildren;

  ///是否列表刷新后 之前所显示的显示  （展开的效果）
  String? onclickId = '';

  /// 评论用户名称 点击后名字
  RxString clickPullName = ''.obs;
  String clickPullNameP = '';

  ///	评论用户ID
  String clickPullNameParentID = '';
  String clickPullNameParentIDP = '';

  /// 评论父级ID
  String clickPullNamePidParentID = '';
  String clickPullNamePidParentIDP = '';

  /// 回复评论
  String userAddCommentDialog = '';

  ///	时间排序 0：降序 1：升序
  bool order = true;

  // 获取数据 全部的数据
  Future<List<EducationCommentListEntity>> listCommentAll(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<EducationCommentListEntity>>(
      Interface.listComment,
      queryParameters: {
        'commentContent': searchX, //	模糊查询评论内容
        'commentType': 1, //	类型 0：评价 1：问答
        'textbookId': Get.arguments['id'], //课程ID
      },
    ).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
        update();
      }
    });
    return list!;
  }

  // 获取数据 全部的数据
  Future<List<EducationCommentListEntity>> listCommentMe(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<EducationCommentListEntity>>(
      Interface.listComment,
      queryParameters: {
        'pageNum': index,
        'pageSize': size,
        'commentContent': searchX, //	我的评论内容
        'commentType': 1, //	类型 0：评价 1：问答
        'textbookId': Get.arguments['id'], //课程ID
        'type': 1, //	1：我的
      },
    ).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        listMe = result.data;
        update();
      }
    });
    return listMe!;
  }

  //切换数据
  void allDateOrMeDate(bool who) {
    this.who = who;
    update();
    Timer(const Duration(milliseconds: 500), () {
      globalKey.currentState?.onRefresh();
    });
  }

  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  ///删除评论
  void educationCommentDel(String? id) async {
    final res = await HttpUtil().generateDeleteRequest(
      Interface.educationCommentDel,
      queryParameters: {
        'id': id,
      },
    ).execute();
    res.onSuccess((result) {
      globalKey.currentState?.onRefresh();
      AppToast.showSuccess('删除${result.message}');
    });
  }

  ///发表问题
  void evaluateInfo() async {
    if (userAddComment.isEmpty) {
      AppToast.showWarning('请输入评价');
      return;
    }
    final res = await HttpUtil().generatePostRequest(
      Interface.addComment,
      data: {
        'commentContent': userAddComment, //评论内容
        'commentType': 1, //0：评价 1：问答
        'textbookId': Get.arguments['id'], //课程ID
      },
    ).execute();
    res.onSuccess((result) {
      FocusManager.instance.primaryFocus?.unfocus();
      AppToast.showSuccess('评论${result.message}');
      userAddComment = '';
      globalKey.currentState?.onRefresh();
      update();
    });
    res.onError((result) {});
  }

  ///回复评论
  void evaluateInfoCommentDialog() async {
    if (userAddCommentDialog.isEmpty) {
      AppToast.showWarning('请输入评论内容');
      return;
    }
    final res = await HttpUtil().generatePostRequest(
      Interface.addComment,
      data: {
        'commentContent': userAddCommentDialog, //评论内容
        'commentPid': clickPullNamePidParentID, //	评论父级ID
        'commentType': 1, //0：评价 1：问答
        'textbookId': Get.arguments['id'], //课程ID
      },
    ).execute();
    res.onSuccess((result) {
      FocusManager.instance.primaryFocus?.unfocus();
      AppToast.showSuccess('评论${result.message}');
      userAddCommentDialog = '';
      globalKeyDialog.currentState?.onRefresh();
      //如果当前item设置显示

      update();
    });
    res.onError((result) {});
  }

  ///最外层对象
  GetChildrenEntity? getChildrenEntity;

  ///最外层对象下Children
  List<GetChildrenChildren>? listGetChildrenChildren = [];

  //查询子集问答列表
  Future<List<GetChildrenChildren>> getChildrenE(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<GetChildrenEntity>>(
      Interface.getChildren,
      queryParameters: {
        'commentPid': firstLevelCommentId, //commentPid 点击那个条目的id
        'order': order ? 0 : 1, //	时间排序 0：降序 1：升序
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getChildrenEntity = result.data?[0];
        listGetChildrenChildren = result.data?[0].children!;
        for (var commentLikeX in listGetChildrenChildren!) {
          // commentLikeX.commentLikeX?.value = commentLikeX.commentLike ?? 0;
          for (var commentLikeXX in commentLikeX.children!) {
            commentLikeXX.commentLikeX?.value = commentLikeXX.commentLike ?? 0;
          }
          if (onclickId != null && onclickId!.isNotEmpty && commentLikeX.id == onclickId) {
            commentLikeX.isShow.value = true;
            //将当前选中的条目重新赋值给上一个节点（因为在下次点击情况下 找不到当前的节点 刷新造成的！！！！！！！！！！！！！！！！！！！！！！）
            tobGetChildrenChildren = commentLikeX;
          }
        }
        update();
      }
    });
    return listGetChildrenChildren!;
  }

  ///评价点赞
  void onClickGetChildrenChildrenChildren(GetChildrenChildrenChildren e) async {
    final res = await HttpUtil().generateGetRequest(
      Interface.commentLike,
      queryParameters: {'commentId': e.id},
    ).execute();
    res.onSuccess((result) {
      e.commentLikeXOnclick = !e.commentLikeXOnclick;
      //成功过后不刷列表直接加一或减一
      if (e.commentLikeXOnclick) {
        e.commentLikeX?.value++;
      } else {
        e.commentLikeX?.value--;
      }
    });
  }

  ///评价点赞
  void onClickGetChildrenChildren(GetChildrenChildren e) async {
    final res = await HttpUtil().generateGetRequest(
      Interface.commentLike,
      queryParameters: {'commentId': e.id},
    ).execute();
    res.onSuccess((result) {
      e.commentLikeXOnclick = !e.commentLikeXOnclick;
      //成功过后不刷列表直接加一或减一
      if (e.commentLikeXOnclick) {
        e.commentLikeX?.value++;
      } else {
        e.commentLikeX?.value--;
      }
    });
  }

  //调出键盘：
  void callKeyboardShow() {
    SystemChannels.textInput.invokeMethod<void>('TextInput.show');
  }

  //隐藏键盘：
  void callKeyboardHide() {
    SystemChannels.textInput.invokeMethod<void>('TextInput.hide');
  }

  @override
  void onInit() {
    super.onInit();
    focusNode2.addListener(() {
      //获取焦点 通过列表调整搜索框高度
      if (focusNode2.hasFocus) {
        globalKey.currentState?.getController()?.animateTo(
              1.w, // 每个条目的高度
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
      } else {
        globalKey.currentState?.getController()?.animateTo(
              0.w, // 每个条目的高度
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    listCommentMe(1, 20);
  }
}
